import { useEffect } from 'react'
import { useMeta, useLog } from '@/stores'
import { Space, Button } from 'tdesign-react'
import KeepAlive from 'react-activation'
import styles from './index.module.less'
import { Conf as Store } from 'electron-conf/renderer'

const electronStore = new Store()
const Log = (_: any) => {

  const { log, setLog } = useLog()

  useEffect(() => {
    electronStore.get('log').then((log: any) => {
      setLog(log || [], 'overwrite')
    })
    window.electron.ipcRenderer.on('log', async (_, data: { type: 'info' | 'error' | 'success' | 'warning', log: string }) => {
      console.log(data)
      setLog([data])
    })
    return () => {
      window.electron.ipcRenderer.removeAllListeners('log')
    }
  }, [])

  const clearLog = () => {
    electronStore.set('log', [])
    setLog([], 'overwrite')
  }

  return <div className={styles.Log}>
    <div className={'content-wrapper'}>
      <Space direction={'vertical'}><Button onClick={clearLog}>清空日志</Button></Space>
      <div className={styles.preWrap}>{log.map((item: any) => item.log)}</div>
    </div>
  </div>
}

const KeepAliveComponent = (props: any) => {

  const { setMeta } = useMeta()

  useEffect(() => {
    setMeta('日志', 'menu-page')
  }, [])

  return <KeepAlive name='log' key='log'>
    <Log
      {...props}
    />
  </KeepAlive>
}


export default KeepAliveComponent
